package com.zelic.zwrite;

import java.io.*;
import android.app.*;
import android.graphics.*;
import android.os.Bundle;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import com.zelic.znn.*;
import com.zelic.image.*;
import java.util.*;

import org.w3c.dom.Text;

public class ZWriteActivity extends Activity {

	WriteView writeView;
	Button getImage;
	TextView result;
	Network network;
	Bitmap image;
	double[] input;
	double[] output;

	private String[] charArray = new String[] { "A", "Ă", "Â", "B", "C", "D",
			"Đ", "E", "Ê", "F", "G", "H", "K", "I", "J", "L", "M", "N", "O",
			"Ô", "Ơ", "P", "Q", "R", "S", "T", "U", "Ư", "V", "W", "X", "Y",
			"Z", "a", "ă", "â", "b", "c", "d", "đ", "e", "ê", "f", "g", "h",
			"k", "i", "j", "l", "m", "n", "o", "ô", "ơ", "p", "q", "r", "s",
			"t", "u", "ư", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4",
			"5", "6", "7", "8", "9" };
	private List<String> charset;

	private void init() {
		charset = Arrays.asList(charArray);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			network = Network.importNetworkFromFile(new BufferedInputStream(
					getResources().openRawResource(R.raw.netconfig)));
		} catch (IOException e) {
			e.printStackTrace();
		}
		init();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		writeView = (WriteView) findViewById(R.id.writeView);
		writeView.setDrawingCacheEnabled(true);
		getImage = (Button) findViewById(R.id.btnGetImage);
		result = (TextView) findViewById(R.id.tvResult);
		getImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				image = writeView.getImage();
				input = Util.flattenIntMatrix(ImageTransformer.getScaledImage(
						8, 8, ImageTransformer
								.getMinimalImageMatrix(getBinaryImage(image))));
				output = network.use(input);
				int pos = Util.getPositionFromResult(output);
				result.setText(charset.get(pos));
				writeView.resetView();
			}
		});

	}

	private int[][] getBinaryImage(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int[][] result = new int[height][width];
		for (int i = 0; i < height; i++) {
			for (int j = 0; j < width; j++) {
				int temp = bitmap.getPixel(j, i);
				if (temp == Color.WHITE) {
					result[i][j] = -1;
				} else {
					result[i][j] = 1;
				}
			}
		}
		return result;
	}
}